package com.song.service.impl;

import com.song.context.BaseContext;
import com.song.dto.ShoppingCartDTO;
import com.song.entity.Setmeal;

import com.song.entity.ShoppingCart;
import com.song.mapper.CartMapper;
import com.song.mapper.DishMapper;
import com.song.mapper.SetmealMapper;
import com.song.service.ShoppingCartService;

import com.song.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public void addCart(ShoppingCartDTO shoppingCartDTO) {
        //判断购物车中是否有该商品,有则修改数量,没有则添加
        //1.获取购物车中的数据
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> count = cartMapper.getCartCount(shoppingCart);
        if(!count.isEmpty()){
            ShoppingCart cart = count.get(0);
            cart.setNumber(cart.getNumber()+1);
            cartMapper.updateCart(cart);
        }else {
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            if(shoppingCart.getDishId()!=null){
              DishVO dishVO = dishMapper.getDishByID(shoppingCart.getDishId());
              shoppingCart.setName(dishVO.getName());
              shoppingCart.setImage(dishVO.getImage());
              shoppingCart.setAmount(dishVO.getPrice());

            }else {
                Setmeal setmeal = setmealMapper.getSetmealById(shoppingCart.getSetmealId());
                shoppingCart.setAmount(setmeal.getPrice());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());

            }
            cartMapper.insertCart(shoppingCart);

        }
    }

    @Override
    public List<ShoppingCart> getCartList() {
        // 获取当前用户
        Long userId = BaseContext.getCurrentId();
       //根据用户ID查询购物车数据
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        return cartMapper.getCartCount(shoppingCart);
    }

    @Override
    public void cleanCart() {
        Long userId = BaseContext.getCurrentId();
        cartMapper.cleanCart(userId);
    }

    @Override
    public void subCart(ShoppingCartDTO shoppingCartDTO) {
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(userId);
        cartMapper.delCartOne(shoppingCart);
    }

}
